//
//  AppDelegate.m
//  Rong360
//
//  Created by tianliwei on 25/1/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//

#import "AppDelegate.h"
#import "TacticsViewController.h"
#import "CityListViewController.h"
#import "CommonToolsViewController.h"
#import "LoanEnquiryViewController.h"
#import "APService.h"
#import "ParseUtil.h"
#import "RequestUtil.h"
#import "SignUtil.h"
#import "MsgInfo.h"
#import "MD5Util.h"
#import "NetCheckUtil.h"
//友盟统计
#import "MobClick.h"
#import "UMSocial.h"
#import "WebViewController.h"

//引入Parse框架
//#import "Parse/Parse.h"

//引入微信
#import "WXApi.h"
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [UiUtil globalUI];
    [[DBMan shareDB]initAllTableOfDB];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateCity)
                                                 name:kUpdateCityNotification
                                               object:nil];
    //增加标识，用于判断是否是第一次启动应用...
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        if (![NetCheckUtil isNetworkRunning]) {
            [[Config shareConfig] getDefaultConfig];
        }
    }
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];
    
    NSString *token = [MD5Util md5:TokenKey];
    NSString *configUrl = [NSString stringWithFormat:@"%@?token=%@",ConfigUrl,token];
    NSLog(@"configUrl:======> %@\n",configUrl);
    
    NSString *cityUrl = [NSString stringWithFormat:@"%@?token=%@",CityUrl,token];
    NSLog(@"cityUrl:======> %@\n",cityUrl);
    [[Config shareConfig] getConfigFromServerUrl:configUrl];
    [[Config shareConfig] getCitiesFromServerUrl:cityUrl];
    
    //////////////////////////////////////////////////////////////////
    
    NSArray *quesIDs = [[DBMan shareDB]getAllSectionQuesIDInQAInfo];
    NSString *questions = [quesIDs componentsJoinedByString:@"|"];
    NSString *replyPara = [NSString stringWithFormat:@"ask_id=%@",questions];
    NSString *replyUrl = [NSString stringWithFormat:@"%@?%@&token=%@",ReplyUrl,replyPara,[SignUtil stringFromURL:replyPara]];
    NSLog(@"replyUrl:======> %@\n",replyUrl);
    [RequestUtil requestWithType:Answer Url:replyUrl];
    
    [RequestUtil requestWithType:Recommend Url:RecommendUrl];

    //////////////////////////////////////////////////////////////////
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    self.tacticsVC = [[TacticsViewController alloc]init];
    UINavigationController *tacticsNavi = [[UINavigationController alloc]initWithRootViewController:self.tacticsVC];
    self.commonToolsVC = [[CommonToolsViewController alloc]init];
    UINavigationController *commonToolsNavi = [[UINavigationController alloc]initWithRootViewController:self.commonToolsVC];
    self.loanEnquiryVC = [[LoanEnquiryViewController alloc]init];
    UINavigationController *loanEnquiryNavi = [[UINavigationController alloc]initWithRootViewController:self.loanEnquiryVC];
    self.tabbarVC = [[UITabBarController alloc]init];
    [self.tabbarVC.tabBar setBackgroundImage:[[UIImage imageNamed:@"tabbar_bg"]stretchableImageWithLeftCapWidth:1 topCapHeight:1]];
    [self.tabbarVC.tabBar setSelectionIndicatorImage:[[UIImage imageNamed:@"tabbar_bg"]stretchableImageWithLeftCapWidth:1 topCapHeight:1]];
    self.tabbarVC.viewControllers = @[commonToolsNavi,tacticsNavi,loanEnquiryNavi];
    self.tabbarVC.delegate = self;
    self.tabbarVC.selectedIndex = 1;
    self.window.rootViewController = self.tabbarVC;
    [self.window makeKeyAndVisible];
    
    
    /*>>>>>>>>>>>>>>>>>>>>>>>> 友盟分享、统计 >>>>>>>>>>>>>>>>>>>>>>>>*/
    
    [MobClick startWithAppkey:kUMSocialKey];
    
    //友盟自动更新
    [MobClick checkUpdate];
    //[MobClick setLogEnabled:YES];

    //友盟社会化组件
    [UMSocialData setAppKey:kUMSocialKey];
    
    /*[UMSocialConfig setSupportQzoneSSO:YES importClasses:@[[QQApiInterface class],[TencentOAuth class]]];
     [UMSocialConfig setShareQzoneWithQQSDK:YES url:kRong360Host importClasses:@[[QQApiInterface class],[TencentOAuth class]]];*/
    
    /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
    
    
    /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>消息推送>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    [defaultCenter addObserver:self selector:@selector(networkDidSetup:) name:kAPNetworkDidSetupNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidClose:) name:kAPNetworkDidCloseNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidRegister:) name:kAPNetworkDidRegisterNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kAPNetworkDidLoginNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kAPNetworkDidReceiveMessageNotification object:nil];
    
    [self.window makeKeyAndVisible];
    
    [[NSUserDefaults standardUserDefaults]setObject:[APService openUDID] forKey:kOpenUdid];
    NSLog(@"====>OpenUDID:%@\n",[APService openUDID]);
    
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)];
    [APService setupWithOption:launchOptions];
    
    //给城市设标签
    NSString *currentCity = [[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCity];
    if (currentCity) {
        [APService setTags:[NSSet setWithObject:currentCity] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    }
    
    /*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/
    
    return YES;
}


- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if (tabBarController.selectedIndex == 2) {
        if (![[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCity]) {
            CityListViewController *cityVC = [[CityListViewController alloc]init];
            cityVC.dismissStyle = LoanEnquiry;
            cityVC.delegate = self.loanEnquiryVC;
            UINavigationController *naviVC = [[UINavigationController alloc]initWithRootViewController:cityVC];
            [self.loanEnquiryVC presentModalViewController:naviVC animated:YES];
        }
    }
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    self.tabbarLastIndex = tabBarController.selectedIndex;
    NSLog(@"%d",self.tabbarLastIndex);
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    //////////////////////////////////////////////////////////////////
    
    NSArray *quesIDs = [[DBMan shareDB]getAllSectionQuesIDInQAInfo];
    NSString *questions = [quesIDs componentsJoinedByString:@"|"];
    NSString *replyPara = [NSString stringWithFormat:@"ask_id=%@",questions];
    NSString *replyUrl = [NSString stringWithFormat:@"%@?%@&token=%@",ReplyUrl,replyPara,[SignUtil stringFromURL:replyPara]];
    NSLog(@"replyUrl:======> %@\n",replyUrl);
    [RequestUtil requestWithType:Answer Url:replyUrl];
    
    //////////////////////////////////////////////////////////////////
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [UMSocialSnsService  applicationDidBecomeActive];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得自定义字段内容
    NSString *pushUrl = [userInfo valueForKey:@"PushUrl"]; //自定义参数，key是自己定义的
    NSLog(@"content =[%@], badge=[%d], sound=[%@], push url =[%@]",content,badge,sound,pushUrl);
   
    [APService handleRemoteNotification:userInfo];
    
     WebViewController *webVC = [[WebViewController alloc]initWithUrl:pushUrl title:content];
    webVC.type = HTML5ShareUrl;
    webVC.push = YES;
    UINavigationController *naviVC = [[UINavigationController alloc]initWithRootViewController:webVC];
    [self.tabbarVC presentModalViewController:naviVC animated:YES];
}


//avoid compile error for sdk under 7.0
#ifdef __IPHONE_7_0
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得自定义字段内容
    NSString *pushUrl = [userInfo valueForKey:@"PushUrl"]; //自定义参数，key是自己定义的
    NSLog(@"content =[%@], badge=[%d], sound=[%@], push url =[%@]",content,badge,sound,pushUrl);
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNoData);
    WebViewController *webVC = [[WebViewController alloc]initWithUrl:pushUrl title:content];
    webVC.type = HTML5ShareUrl;
    webVC.push = YES;
    UINavigationController *naviVC = [[UINavigationController alloc]initWithRootViewController:webVC];
    [self.tabbarVC presentModalViewController:naviVC animated:YES];

}
#endif


#pragma mark -

- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"未连接。。。");
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"已注册");
}

- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *title = [userInfo valueForKey:@"title"];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    
    NSString *msgInfo = [NSString stringWithFormat:@"收到消息\ndate:%@\ntitle:%@\ncontent:%@", [dateFormatter stringFromDate:[NSDate date]],title,content];
    NSLog(@"===>msgInfo:%@",msgInfo);
    [[NSNotificationCenter defaultCenter]postNotificationName:kNewMsgNotification object:nil userInfo:nil];
    
}


- (void)updateCity{
    //给城市设标签
    NSString *currentCity = [[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCity];
    if (currentCity) {
        [APService setTags:[NSSet setWithObject:currentCity] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    }
}

- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}


@end
